import React from 'react';
import { withRouter } from 'react-router';
import { connect } from 'react-redux';
import Dialog from 'rc-dialog';
import Input from '../base/Input.js';
import InputNumber from '../base/InputNumber.js';
import officialChannelAction from '../../actions/officialChannelAction.js';
import Widget from '../mui/Widget.js';
import HoverMessageVer from '../mui/hoverMessageVer.js';

// import validate from '../../utils/Validate.js';

const formChannel = withRouter(
  React.createClass({
    getInitialState() {
      return {
        buttonState: false,
        visible: false,
        verError: false,
        clsno: '',
        formData: {
          name: '',
          ver: '',
          remark: ''
        },
      };
    },
    componentWillMount() {
      this.props.router.setRouteLeaveHook(
        this.props.route,
        this.routerWillLeave
      );
    },
    componentDidMount() {
    // 判断是否传入id(编辑功能)
    // ==================
      const { params, getOneChannel } = this.props;
      if (params.id) {
        getOneChannel({ channel_id: params.id });
      }
    },
    componentWillReceiveProps(nextProps) {
      const { oneChannel } = nextProps;
      if (this._flag) {
        return;
      }
      this._flag = true;
      if (this.props.params.id) {
        const fData = this.state.formData;
        fData.name = oneChannel.data.name;
        fData.ver = oneChannel.data.ver;
        fData.remark = oneChannel.data.remark;
        this.setState({
          formData: fData,
          clsno: oneChannel.data.clsno,
          buttonState: true
        });
      }
    },
    // 离开清理数据
    // ===========
    componentWillUnmount() {
      this.props.restoreChannel();
    },
    routerWillLeave() {
      const { formData } = this.state;
      if (this.leaveFlag) {
        return true;
      }
      for (const key in formData) {
        if (formData[key]) {
          return '是否放弃保存当前页面并跳转';
        }
      }
    },
    onClose() {
      this.setState({
        visible: false,
      });
      const { editChannel, router, params } = this.props;
      const data = this.state.formData;
      data.channel_id = params.id;
      data.status = 0;
      this.leaveFlag = true;
      editChannel(data, router);
    },
    handleChange(targetData) {
      // 序列化表单
      // ============
      const fData = this.state.formData;
      const regNum = /[^0-9]/g;
      if (targetData.name === 'ver' && regNum.test(targetData.value)) {
        return;
      }
      fData[targetData.name] = targetData.value;
      this.setState({
        formData: fData,
      });
      // 如果有为空情况，不能点击保存按钮
      // ==============================
      if (fData.status === 0) {
        fData.status = '0';
      }
      for (const key in fData) {
        if (!fData[key] && key !== 'remark') {
          this.setState({ buttonState: false });
          break;
        } else {
          this.setState({ buttonState: true });
        }
      }
    },
    handleBlur(targetData) {
      // 清空服务器返回错误信息，例如某条数据重复
      const { resetSaveMsg } = this.props;
      resetSaveMsg();
      if (targetData.value.length < 3) {
        this.setState({ verError: true });
      } else {
        this.setState({ verError: false });
      }
    },
    handleSubmit(event) {
      event.preventDefault();
      // $(this.refs.formbox).find('input,textarea').trigger('focus').trigger('blur');
      if ($('.form-error').length) {
        return;
      }
      const { newChannel, editChannel, router, params } = this.props;
      const data = this.state.formData;
      data.status = 1;
      this.leaveFlag = true;
      if (!params.id) {
        newChannel(data, router);
      } else {
        data.channel_id = params.id;
        editChannel(data, router);
      }
    },
    cancel() {
      this.leaveFlag = true;
      this.props.router.push('/official/channel');
    },
    lockChannel() {
      this.setState({ visible: true });
    },
    cancelReturn() {
      this.setState({
        visible: false,
      });
    },
    render() {
      // console.log('00000')
      // console.log(this.state.formData)
      const { saveMsg, params } = this.props;
      const button = <button className={params.id ? 'btn btn-primary w120 mr60' : 'btn btn-primary'} onClick={this.handleSubmit}>保存</button>;
      const disableButton = <button className="btn btn-disable" disabled="disabled">保存</button>;
      const lockButton = <button className="btn btn-red w120 mr60" onClick={this.lockChannel}>冻结</button>;
      let clsnoValue;
      if (params.id) {
        clsnoValue = <p className="init-message">{this.state.clsno}</p>;
      } else {
        clsnoValue = <p className="init-message">添加渠道后自动生成</p>;
      }
      let dialog;
      if (this.state.visible || !this.state.destroyOnClose) {
        dialog = (
          <Dialog
            visible={this.state.visible}
            animation="slide-fade"
            maskAnimation="fade"
            // onClose={this.cancelReturn}
            style={{ width: 420 }}
            // title={<div>第二个弹框</div>}
            footer={
            [
              <button type="button" className="btn btn-cancel w120 mr60" key="close" onClick={this.onClose} >
                确定
              </button>,
              <button type="button" className="btn btn-primary w120" key="save" onClick={this.cancelReturn} >
                取消
              </button>,
            ]
            }
          >
            <div className="confirm-dialog-body">
              <p className="dialog-message">是否确定冻结</p>
              <p className="fixed-width-text package-name">{this.state.formData.name}</p>
            </div>
          </Dialog>
        );
      }
      // const v1 = { data : {} };
      // v1.data[validate.number] = '该渠道码有误，不可使用';
      // v1.minLengthChar = { min:3, message:'该渠道码有误，不可使用' };
      const { verError } = this.state
      return (
        <div className="mw600">
          <Widget widgetHeader={'正式渠道列表'} widgetHeaderTwo={params.id ? '编辑渠道' : '添加渠道'} />
          <div className="f-group-480">
            <div className="form-group">
              <label className="control-label w150" htmlFor="name">名称</label>
              <div className="input-group">
                <Input
                  data-target="name"
                  type="text"
                  value={this.state.formData.name}
                  onChange={this.handleChange}
                  placeholder="(必填，不可重复，允许包含汉字、字母、数字及常用的特殊字符)"
                  maxLength={128}
                />
              </div>
              {saveMsg.name === 'name' ? <span className="form-out-error text-danger" >名称已存在，请重新输入</span> : ''}
            </div>
            <div className="form-group">
              <label className="control-label w150" htmlFor="name">内部版本渠道识别码</label>
              <div className="input-group">
                <InputNumber
                  data-target="ver"
                  type="text"
                  onChange={this.handleChange}
                  onBlur={this.handleBlur}
                  value={this.state.formData.ver}
                  placeholder="(必填, 3位数字)"
                  maxLength={3}
                />
                <HoverMessageVer />
                {verError ? <span className="form-error text-danger">格式错误，请填写3位数字</span> : ''}
              </div>
              {saveMsg.name === 'ver' ? <span className="form-out-error text-danger" >该渠道识别码已存在，请重新输入</span> : ''}
            </div>
            <div className="form-group">
              <label className="control-label w150" htmlFor="md5">渠道ID</label>
              <div className="input-group">
                {clsnoValue}
              </div>
            </div>
            <div className="form-group">
              <label className="control-label w150" htmlFor="remark">备注</label>
              <div className="input-group placeholder-normal">
                <Input
                  data-target="remark"
                  type="textarea"
                  onChange={this.handleChange}
                  value={this.state.formData.remark}
                  rows={'4'}
                  placeholder="(选填)"
                />
              </div>
            </div>
            <div className="ml168">
              {params.id ? lockButton : ''}
              {this.state.buttonState ? button : disableButton}
              <button className={params.id ? 'btn btn-cancel w120' : 'btn btn-cancel ml48'} onClick={this.cancel}>
                取消
              </button>
            </div>
          </div>
          {dialog}
        </div>
      );
    },
  })
);

const mapStateToProps = function (state) {
  return {
    oneChannel: state.officialChannel.oneChannel,
    saveMsg: state.officialChannel.saveMsg
  };
};

module.exports = connect(mapStateToProps, officialChannelAction)(formChannel);
